package com.wshl.aijiuunion.controller.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.OkGo;
import com.nanchen.compresshelper.CompressHelper;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.DialogUtil;
import com.wshl.aijiuunion.utils.GlideUtils;
import com.wshl.aijiuunion.view.bean.GroupNumBean;
import com.wshl.aijiuunion.view.bean.ShenqingJIamengBean;
import com.wshl.aijiuunion.view.widget.AreaDialog;
import com.wshl.aijiuunion.view.widget.NofastClickTextview;
import com.wshl.aijiuunion.view.widget.RoundCornerImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;

/**
 * Created buy 风凊扬 on 2019/10/31 0031
 */
public class ShengjiActivity extends TakePhotoActivity implements BGASortableNinePhotoLayout.Delegate, DialogUtil.OnBottomDilogClick {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_shenfenzheng)
    EditText etShenfenzheng;
    @BindView(R.id.tv_shenfenzheng)
    TextView tvShenfenzheng;
    @BindView(R.id.imgz_shenfenzheng1)
    RoundCornerImageView imgzShenfenzheng1;
    @BindView(R.id.imgz_shenfenzheng2)
    RoundCornerImageView imgzShenfenzheng2;

    @BindView(R.id.et_company)
    EditText etCompany;
    @BindView(R.id.bga_fabusimgs)
    BGASortableNinePhotoLayout bgaFabusimgs;
    @BindView(R.id.et_drtail_address)
    EditText etDrtailAddress;
    @BindView(R.id.tv_confirm)
    NofastClickTextview tvConfirm;
    @BindView(R.id.img_yingyezhizhao)
    RoundCornerImageView imgYingyezhizhao;
    @BindView(R.id.ll_yingye1)
    LinearLayout llYingye1;
    @BindView(R.id.ll_gongsi)
    LinearLayout llGongsi;
    @BindView(R.id.ll_gongsi1)
    LinearLayout llGongsi1;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_aijiu_shuliang)
    TextView tvAijiuShuliang;

    private CompressConfig compressConfig;
    private TakePhoto takePhoto;
    private Uri imageUri;

    private RequestModel requestModel;
    private String shenfengzheng1, shenfengzheng2, yingyezhizhao;
    private List<String> imglist;
    private String type1;
    private String provinceid;
    private String areaid;
    private String cityid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setContentView(R.layout.activity_shengji);
        ButterKnife.bind(this);
        BarUtils.setWhiteStatusBarForActivity(this);

        Intent intent = getIntent();
        type1 = intent.getStringExtra("type");
        switch (type1) {
            case "1":
                tvTopTitle.setText("合作分公司");
                showView();
                break;
            case "2":
                tvTopTitle.setText("合作县级代理");
                showView();
                break;
            case "3":
                tvTopTitle.setText("合作业务员");
                break;
        }

        requestModel = new RequestModel();

        bgaFabusimgs.setDelegate(this);

        //图片选择器
        takePhoto = getTakePhoto();
        //压缩图片(压缩到200k以内)
        compressConfig = new CompressConfig.Builder().setMaxSize(200 * 1024).create();
        takePhoto.onEnableCompress(compressConfig, false);//设置压缩时参数,不显示压缩时的对话框
        DialogUtil.setOnBottomDilogClick(this);

        imglist = new ArrayList<>();
        groupnum();
    }

    private void groupnum() {
        requestModel.GROUPNUM(this, type1, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                GroupNumBean groupNumBean = GsonUtils.fromJson(response, GroupNumBean.class);
                GroupNumBean.DataBean data = groupNumBean.getData();
                String group_num = data.getGroup_num();
                tvAijiuShuliang.setText(group_num + "");
            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    private void showView() {
        llGongsi.setVisibility(View.VISIBLE);
        llGongsi1.setVisibility(View.VISIBLE);
        llYingye1.setVisibility(View.VISIBLE);
    }


    private int type = 1;

    @OnClick({R.id.tv_address, R.id.img_yingyezhizhao, R.id.img_back, R.id.imgz_shenfenzheng1, R.id.imgz_shenfenzheng2, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_address:
                showAreaDialog();
                break;
            case R.id.img_back:
                this.finish();
                break;
            case R.id.imgz_shenfenzheng1:
                type = 1;
                DialogUtil.showBottomDialog(ShengjiActivity.this, "拍照", "相册", "", "#57BE6A", "#57BE6A", "#57BE6A");
                break;
            case R.id.imgz_shenfenzheng2:
                type = 2;
                DialogUtil.showBottomDialog(ShengjiActivity.this, "拍照", "相册", "", "#57BE6A", "#57BE6A", "#57BE6A");
                break;
            case R.id.img_yingyezhizhao:
                type = 3;
                DialogUtil.showBottomDialog(ShengjiActivity.this, "拍照", "相册", "", "#57BE6A", "#57BE6A", "#57BE6A");
                break;
            case R.id.tv_confirm:
                ShenqingJIamengBean bean = new ShenqingJIamengBean();
                bean.setName(etName.getText().toString().trim());
                bean.setMobile(etMobile.getText().toString().trim());
                bean.setShenfencode(etShenfenzheng.getText().toString().trim());
                bean.setCompanyname(etCompany.getText().toString().trim());
                bean.setType(type1);
                bean.setAreaid(areaid);
                bean.setProvinceid(provinceid);
                bean.setCityid(cityid);
                bean.setDetailaddress(etDrtailAddress.getText().toString().trim());
                bean.setImglist(imglist);
                bean.setYingyezhizhaoimg(yingyezhizhao);
                bean.setShenfengzheng(shenfengzheng1);
                bean.setShenfenfan(shenfengzheng2);

                requestModel.jiameng(ShengjiActivity.this, bean, new RequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        ActivityUtils.startActivity(ShenqingSuccessActivity.class);
                        ShengjiActivity.this.finish();
                    }

                    @Override
                    public void onError(int code) {

                    }

                    @Override
                    public void onIntentError() {

                    }
                });
                break;
        }
    }

    private void showAreaDialog() {

        final AreaDialog dialog = new AreaDialog(this, R.style.recharge_pay_dialog);
        dialog.show();
        dialog.setNoOnclickListener(new AreaDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                dialog.dismiss();
            }
        });

        dialog.setYesOnclickListener(new AreaDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                dialog.dismiss();
            }

            @Override
            public void getItemContent(String province, String cityname, String countryname, String area) {

            }


            @Override
            public void getcontent(String address) {
                LogUtils.i("address:" + address);
                tvAddress.setText(address);

            }

            @Override
            public void setProvinceid(String selsectItem1id) {
                LogUtils.i("市:" + selsectItem1id);
                cityid = selsectItem1id;
            }

            @Override
            public void setCityid(String selsectItem2id) {
                LogUtils.i("县id:" + selsectItem2id);
                areaid = selsectItem2id;
            }

            @Override
            public void setCountryid(String selsectItem3id) {

            }

            @Override
            public void setAreaid(String selsectItem4id) {
                LogUtils.i("省id:" + selsectItem4id);
                provinceid = selsectItem4id;

            }
        });
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = AbsListView.LayoutParams.MATCH_PARENT;
        lp.y = 0;
        //设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {

        XXPermissions.with(this)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                // .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        File takePhotoDir = new File(GlobConstant.SDCARD_DIR, GlobConstant.IMAGE_CACHE_DIR);
                        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(ShengjiActivity.this)
                                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                                //  .maxChooseCount(bgaFabusimgs.getMaxItemCount() - bgaFabusimgs.getItemCount()) // 图片选择张数的最大值
                                .maxChooseCount(1)
                                .selectedPhotos(null) // 当前已选中的图片路径集合
                                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                                .build();

                        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //如果权限被永久禁止,quick值为true
                        //让用户手动打开权限设置

                        if (quick) {
                            // dsdsd
                            ToastUtils.showLong("请打开APP拍照和存储权限");
                        }

                    }
                });
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        sortableNinePhotoLayout.removeItem(position);
        if (imglist != null && imglist.size() > 0) {
            imglist.remove(position);
            LogUtils.i("图片:" + imglist.size());
        }
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        //点击图片预览
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(sortableNinePhotoLayout.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        String originalPath = result.getImage().getOriginalPath();
        String compressPath = result.getImage().getCompressPath();//压缩路径
        LogUtils.e("头像路径:" + originalPath);
        LogUtils.e("头像压缩路径:" + compressPath);
        uploadImg(compressPath, type);

    }

    private static final int RC_CHOOSE_PHOTO = 101;//选择图片
    private static final int RC_PHOTO_PREVIEW = 102;//预览已添加的图片

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == RC_CHOOSE_PHOTO) {
                ArrayList<String> selectedPhotos = BGAPhotoPickerActivity.getSelectedPhotos(data);
                LogUtils.i("本次选中的图片的个数:" + selectedPhotos.size());
                if (selectedPhotos.size() == 1) {
                    //图片压缩
                    File compressFile = new CompressHelper.Builder(ShengjiActivity.this)
                            .setMaxWidth(1080)  // 默认最大宽度为1080
                            .setMaxHeight(1920) // 默认最大高度为1920
                            .setQuality(85)    // 默认压缩质量为85
                            .build()
                            .compressToFile(new File(selectedPhotos.get(0)));

                    if (compressFile != null) {
                        //上传图片

                        uploadImg(compressFile.getPath(), 4);

                    }

                    bgaFabusimgs.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));
                }

            }

        }
    }

    /**
     * 上传图片
     *
     * @param path
     * @param type
     */
    private void uploadImg(final String path, final int type) {

        requestModel.uploadImg(this, path, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                switch (type) {
                    case 1:
                        shenfengzheng1 = response;
                        GlideUtils.loadImage(ShengjiActivity.this, path, imgzShenfenzheng1);
                        break;
                    case 2:
                        shenfengzheng2 = response;
                        GlideUtils.loadImage(ShengjiActivity.this, path, imgzShenfenzheng2);
                        break;
                    case 3:
                        yingyezhizhao = response;
                        GlideUtils.loadImage(ShengjiActivity.this, path, imgYingyezhizhao);
                        break;
                    case 4:

                        imglist.add(response);
                        LogUtils.i("图片:" + imglist.size());
                        break;
                }

            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }


    @Override
    public void setTitle1(String title) {
        getImage(title);
    }

    @Override
    public void setTitle2(String title) {
        getImage(title);
    }

    @Override
    public void setTitle3(String title) {

    }

    //获取头像
    private void getImage(final String title) {
        XXPermissions.with(this)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                // .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {

                        File file = new File(GlobConstant.SDCARD_DIR, GlobConstant.IMAGE_CACHE_DIR + System.currentTimeMillis() + ".png");
                        if (!file.getParentFile().exists())
                            file.getParentFile().mkdirs();
                        imageUri = Uri.fromFile(file);

                        takePhoto.onEnableCompress(compressConfig, false);//设置压缩时参数,不显示压缩时的对话框
                        if (title.equals("拍照")) {
                            takePhoto.onPickFromCapture(imageUri);
                            // takePhoto.onPickMultiple(3);

                        } else if (title.equals("相册")) {
                            // takePhoto.onPickMultiple(3);
                            takePhoto.onPickFromGallery();

                        }


                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //如果权限被永久禁止,quick值为true
                        //让用户手动打开权限设置
                        if (quick) {
                            DialogUtil.showNormaldialog(ShengjiActivity.this, "请手动打开权限", false, true);
                            DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                                @Override
                                public void setConfirm() {
                                    XXPermissions.gotoPermissionSettings(ShengjiActivity.this);
                                }

                                @Override
                                public void setCancel() {
                                    ShengjiActivity.this.finish();

                                }

                                @Override
                                public void getInput(String input) {

                                }
                            });

                        }

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
    }
}
